package com.person.leetcode.editor.cn;

import com.sun.org.apache.xpath.internal.operations.And;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.StringJoiner;

/**
 * 43.字符串相乘
 * 2022-05-21 14:51:35
 **/
public class Sequence_0043_MultiplyStrings {
    public static void main(String[] args) {
        Solution solution = new Sequence_0043_MultiplyStrings().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String multiply(String num1, String num2) {
            if ("0".equals(num1) || "0".equals(num2)) {
                return "0";
            }
            int len1 = num1.length();
            int len2 = num2.length();
            String ans = "0";
            for (int i = len1 - 1; i >= 0; i--) {
                int val1 = num1.charAt(i) - '0';
                int add = 0;
                StringBuilder cur = new StringBuilder();
                for (int j = len1 - 1; j > i; j--) {
                    cur.append(0);//进位
                }
                for (int j = len2 - 1; j >= 0; j--) {
                    int val2 = num2.charAt(j) - '0';
                    int val = val2 * val1 + add;
                    cur.append(val % 10);
                    add = val / 10;
                }
                if (add != 0) {//进位
                    cur.append(add % 10);
                }
                ans = addStrings(cur.reverse().toString(), ans);
            }
            return ans;
        }

        public String addStrings(String num1, String num2) {
            int i = num1.length() - 1;
            int j = num2.length() - 1;
            int add = 0;
            StringBuilder ans = new StringBuilder();
            while (i >= 0 || j >= 0 || add != 0) {
                int x = i >= 0 ? num1.charAt(i) - '0' : 0;
                int y = j >= 0 ? num2.charAt(j) - '0' : 0;
                int res = add + y + x;
                ans.append(res % 10);
                add = res / 10;
                i--;
                j--;
            }
            ans.reverse();
            return ans.toString();
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
